<template>
    <div class="reportForms">
        <el-card>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="利润趋势分析" name="trend"></el-tab-pane>
                <el-tab-pane label="利润分析报表" name="profit"></el-tab-pane>
                <el-tab-pane label="收款分析报表" name="payment"></el-tab-pane>
            </el-tabs>
        </el-card>
        <template v-if="activeName == 'trend'">
            <el-card class="marginTop20">
                <span class="_before">账单利润趋势</span>
                <ControlPanel :dataType="3" :timePeriod="timeInterval" :refType = '5' @updateValue='updateLineChart'></ControlPanel>
                <lineChart :config="linConfig"></lineChart>
            </el-card>   
            <el-card class="marginTop20">
                <el-radio-group v-model="profitAnalysis" style="margin-bottom: 30px">
                    <el-radio-button value="profitTrend">客户利润趋势</el-radio-button>
                    <el-radio-button value="profitShare">客户利润占比</el-radio-button>
                </el-radio-group>
                <template v-if="profitAnalysis == 'profitTrend'">
                    <ControlPanel :dataType="3" :timePeriod = "timeInterval" :refType = '5' @updateValue='updateBarChart'></ControlPanel>
                    <barChart :config="barConfig"></barChart>
                </template>
                <template v-if="profitAnalysis == 'profitShare'">
                    <ControlPanel :dataType="3" :timePeriod = "timeInterval" :refType = '5' :currency="'USD'" :isShow="true" @updateValue='updatePieChart'></ControlPanel>
                    <pieChart :config="pieConfig"></pieChart>
                </template>
            </el-card>   
        </template>
        <template  v-if="activeName == 'profit'">
            <el-card class="marginTop20">

            </el-card>
        </template>
        <template  v-if="activeName == 'payment'">
            <el-card class="marginTop20">

            </el-card>
        </template>
    </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref,watch } from 'vue'
import lineChart from '@/views/financialManage/analysis/charts/line'
import barChart from '@/views/financialManage/analysis/charts/bar'
import pieChart from '@/views/financialManage/analysis/charts/pie'
import ControlPanel from '@/views/financialManage/analysis/controlPanel'
import { billProfitCountDate, billProfitCountCompany, billProfitProportionCountCompany} from '@/api/financial/bills'
import { differenceInDays, parse } from 'date-fns';
import { ElMessage } from 'element-plus'
const activeName = ref('trend')
const profitAnalysis = ref("profitTrend")
const timeInterval = ref(["20250715","20250810"]) //查询时间区间

const handleClick = (tab, event) => {
    console.log(tab, event)
}

const linConfig = reactive({
    xAxisData: [],
    yAxisDataUSD: [],
    yAxisDataCNY: []
})  

const barConfig = reactive({
    xAxisData: [],
    yAxisDataUSD: [],
    yAxisDataCNY: []
})  

const pieConfig = reactive({
    xAxisData: [],
    yAxisDataUSD: [],
    yAxisDataCNY: []
})  

//更新折线图
const updateLineChart = async (lineVal) => { 
    let dataType = lineVal.dataType //数据类型: 3-日 5-月份 10-季度 15-年份
    let timePeriod = lineVal.timePeriod
    console.log("timePeriod",timePeriod)
    let refType = lineVal.refType // //账单业务类型 5-租箱  10-回调 20-售箱 25-购箱 30-代管箱
    if(dataType == "3"){ //日期类型 日
        if(timePeriod[0] && timePeriod[1]){
            if(Math.abs(getDateDiff(timePeriod[0],timePeriod[1])) >= 31 ){
                return ElMessage.warning('时间间隔不能超过31天')
            }
        }  
    }
    const resParams = {
        dataType:dataType,
        refType:refType,
        beginDataTime: timePeriod[0],
        endDataTime: timePeriod[1]
    }
    billProfitCountDate(resParams).then(res =>{
        if(res.code == "00000"){
            linConfig.xAxisData.length = 0
            linConfig.yAxisDataUSD.length = 0
            linConfig.yAxisDataCNY.length = 0
            res.data.forEach(item => { 
                let time = item.dataTime.toString().replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")
                linConfig.xAxisData.push(time)
                linConfig.yAxisDataUSD.push(item.usdAmount)
                linConfig.yAxisDataCNY.push(item.cnyAmount) 
           }) 
        }

    })
}
//更新饼状图
const updateBarChart = async (barVal) => { 
    console.log("barVal",barVal)
    let dataType = barVal.dataType
    let timePeriod = barVal.timePeriod
    let refType = barVal.refType
    if(timePeriod && timePeriod.length == 2){
        if(Math.abs(getDateDiff(timePeriod[0],timePeriod[1])) >= 31 ){
            return ElMessage.warning('时间间隔不能超过31天')
        }  
    }else{ 
        return ElMessage.warning('请选择时间区间')
    }

    let resParams = {
        dataType:dataType,
        refType:refType,
        beginDataTime:timePeriod[0],
        endDataTime:timePeriod[1] 
    }
    billProfitCountCompany(resParams).then(res => { 
        console.log("bar",res)
        barConfig.xAxisData.length = 0
        barConfig.yAxisDataUSD.length = 0
        barConfig.yAxisDataCNY.length = 0
        if(res.code == '00000'){
            res.data.forEach((item,index)=>{ 
                if(index < 10){
                    barConfig.xAxisData.push(item.settlementCompanyName)
                    barConfig.yAxisDataUSD.push(item.usdAmount)
                    barConfig.yAxisDataCNY.push(item.cnyAmount) 
                    // xAxisValue.value.push(item.settlementCompanyName)
                    // axisValueUsd.value.push(item.usdAmount)
                    // axisValueCny.value.push(item.cnyAmount)
                }
            })
        }

    })  

}

// 更新饼状图 billProfitProportionCountCompany
const axisPieValueName = ref(['河南亚航','河南陆海'])
const axisPieValue = ref(["10","20"])
const updatePieChart = (pieVal) => { 
    let dataType = pieVal.dataType
    let timePeriod = pieVal.timePeriod
    let refType = pieVal.refType
    let currency = pieVal.currency

    let resParams = {
        dataType:dataType,
        refType:refType,
        currency:currency,
        beginDataTime: timePeriod[0],
        endDataTime: timePeriod[1]
    }
    billProfitProportionCountCompany(resParams).then(res => { 
      axisPieValueName.value.length = 0
      axisPieValue.value.length = 0
      if(res.code == '00000'){
        res.data.forEach((item,index)=>{ 
            if(index < 10){
                axisPieValueName.value.push(item.settlementCompanyName)
                axisPieValue.value.push(item.amount)
            }
        })
      } 
    })
}

function getDateDiff(dateStr1: string, dateStr2: string): number {
  // 1. 解析字符串为 Date 对象
  const parseCustomDate = (str: string) => {
    return parse(str, 'yyyyMMdd', new Date());
  };

  // 2. 直接计算天数差
  return differenceInDays(
    parseCustomDate(dateStr2),
    parseCustomDate(dateStr1)
  );
}
onMounted(() => {
    let cahrtData = {
        dataType:'3',
        timePeriod:["20250715","20250810"],
        refType:'5',
        currency:'USD'
    }
    updateLineChart(cahrtData)
    updateBarChart(cahrtData)
    updatePieChart(cahrtData)
})
watch(() => activeName.value, (val) => {
    console.log("activeName",val) 
    if(val == "trend"){
        let cahrtData = {
            dataType:'3',
            timePeriod:["20250715","20250810"],
            refType:'5',
            currency:'USD'
        }
        updateLineChart(cahrtData)
        updateBarChart(cahrtData)
        updatePieChart(cahrtData)
    }
})
</script>
<style lang="scss" scoped>
    .reportForms{
        padding: 0 20px;
    }
</style>